#include <stdio.h>
#include <SDL/SDL.h>

#define BPP 4
#define DEPTH 32


typedef struct{
	int32_t x,y,z;
}vec;


//TODO use components of eye other than z
//focal point relative to viewport
#define EYE_x 0
#define EYE_y 0
#define EYE_z -520 //60 degree vertical FOV

//Viewport
#define WIDTH 800
#define HEIGHT 600

//not yet used
//normal of viewport
//centric round 0
#define PNORM_x 0
#define PNORM_y 0
#define PNORM_z 1



SDL_Surface *screen;



/*

void DrawScreen(SDL_Surface* screen, int h)
{ 
    int x, y, ytimesw;
  
    if(SDL_MUSTLOCK(screen)) 
    {
        if(SDL_LockSurface(screen) < 0) return;
    }

    for(y = 0; y < screen->h; y++ ) 
    {
        ytimesw = y*screen->pitch/BPP;
        for( x = 0; x < screen->w; x++ ) 
        {
            setpixel(screen, x, ytimesw, (x*x)/256+3*y+h, (y*y)/256+x+h, h);
        }
    }
    if(SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);
  
    SDL_Flip(screen); 
}
*/


void setpixel(int x, int y){
	Uint32 *pixmem32;
	Uint32 colour;  
	
	//TODO segfault for clipping
	x+=WIDTH/2;
	y+=HEIGHT/2;
	
	colour = SDL_MapRGB(screen->format, 255, 255, 255);
	
	((uint32_t*)screen->pixels)[y*WIDTH + x] = colour;
	((uint32_t*)screen->pixels)[y*WIDTH + x-1] = colour;
	((uint32_t*)screen->pixels)[y*WIDTH + x+1] = colour;
	((uint32_t*)screen->pixels)[(y+1)*WIDTH + x] = colour;
	((uint32_t*)screen->pixels)[(y-1)*WIDTH + x] = colour;
}


//TODO
void clip(){
	
}

void rasterize(){
	int i;
	vec ray = {0,0,0};
	vec v[8] = {{-400,-400,200}, {-400,400,200}, {400,-400,200}, {400,400,200}, {-400,-400,1400}, {-400,400,1400}, {400,-400,1400}, {400,400,1400}};
	
	for(i = 0; i < 8; i++){
		ray.x = v[i].x - EYE_x;
		ray.y = v[i].y - EYE_y;
		ray.z = v[i].z - EYE_z;
		
		setpixel(-(ray.x*EYE_z)/ray.z, -(ray.y*EYE_z)/ray.z);//TODO
	}
	
}

void clear(){
	SDL_FillRect(screen, 0, 0x000000);
}

int main(int argc, char* argv[]){
	SDL_Event event;

	int keypress = 0;
	int h=0; 
	int i;

	if (SDL_Init(SDL_INIT_VIDEO) < 0 ) return 1;

	if (!(screen = SDL_SetVideoMode(WIDTH, HEIGHT, DEPTH, SDL_HWSURFACE))){
		SDL_Quit();
		return 1;
	}
	
	clear();
	rasterize();
	SDL_Flip(screen);
	
	while(!keypress){
		//DrawScreen(screen,h++);
		while(SDL_PollEvent(&event)){      
			switch (event.type){
				case SDL_QUIT:
					keypress = 1;
					break;
				case SDL_KEYDOWN:
					keypress = 1;
					break;
			}
		}
	}

	SDL_Quit();

	return 0;
}







